package com.budwk.app.sqfwV2.component.centuryCity;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.dfxyWechatMP.DfxyWeChatMPUtils;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sms.dto.SmsMsgDTO;
import com.budwk.app.sms.service.OpaSmsService;
import com.budwk.app.sms.service.ZtSmsService;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.models.Sqfw_form_summary_pdf;
import com.budwk.app.sqfw.services.SqfwFormSummaryPdfService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfwDoc.bo.PdfGenerateRes;
import com.budwk.app.sqfwDoc.codeGenerator.bo.PdfCreatedBridgeBO;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplatePdfCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwV2.component.BinyangStreetComponent;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskPdfDTO;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.enums.*;
import com.budwk.app.sqfwV2.generator.binyangStreet.pdf.*;
import com.budwk.app.sqfwV2.generator.centuryCitySecurity.pdf.SafetyCheckPdfGenerater;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.wordToPdfAndUpload;

/**
 * 本代码由代码生成器生成，版本号1.0
 */

@Slf4j
@IocBean
public class CenturyCitySecurityPdfService extends SqfwTemplatePdfCommonService {

    @Inject
    private OpaSmsService opaSmsService;

    @Inject
    private ZtSmsService ztSmsService;

    @Inject
    private SqfwFormSummaryPdfService formSummaryPdfService;

    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    @Inject
    private SysUserService userService;

    @Inject
    private SysUnitService unitService;


    @Override
    public AbstractCustomerPdfCreateField getPdfCreateField(Sqfw_formSummary_new formSummary) {
        return JSON.parseObject(formSummary.getParamData(), SafeCheckTaskPdfDTO.class);
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    public String getSummaryType() {
        return SupportBusinessTypeEnum.SAFE_CHECK.getName();
    }

    /**
     * 当pdf生成成功的时候，sock发送什么样的消息至前端
     * 参照{@link SqfwWebSocketMsgConstants}
     *
     * @return 结果
     */
    @Override
    public String getPdfCreateSocketType() {
        return SqfwWebSocketMsgConstants.work_flow_pdf_created;
    }

    /**
     * 创建下载文件的名称
     * 可以参照 {@link DownLoadFileNameEnum}
     * 注意！！！ 不用加上.pdf或者.word后缀
     *
     * @param completeFlow   工作流
     * @param formSummaryNew 表单数据
     * @return 结果
     */
    @Override
    protected String getDownloadFileName(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummaryNew) {
        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSON.parseObject(formSummaryNew.getParamData(), SafeCheckTaskPdfDTO.class);
        BinYangFileServiceEnum serviceEnum = BinYangFileServiceEnum.getByLabel(safeCheckTaskPdfDTO.getType(), formSummaryNew.getDistrict(), formSummaryNew.getCounty());
        if (serviceEnum != null) {
            return StrUtil.format("{}_{}_{}", safeCheckTaskPdfDTO.getPlaceName(), serviceEnum.getFileName(), DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));
        }
        return StrUtil.format("{}_{}_{}", safeCheckTaskPdfDTO.getPlaceName(), DownLoadFileNameEnum.getName(safeCheckTaskPdfDTO.getType()), DateUtil.format(new Date(), "yyyyMMddHHmmss"));
    }

    @Override
    protected void customerPopularPdfCreateParam(SqfwPdfCreateCommonBO pdfCreateCommonBO, Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummary) {

    }

    @Override
    protected List<BaseTemplatePdfGenerator> getPdfGenerator(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummary) {
        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSON.parseObject(formSummary.getParamData(), SafeCheckTaskPdfDTO.class);
        List<BaseTemplatePdfGenerator> generatorList = Lists.newArrayList();
        //因为1.0，2.0并行因此这里根据入口来源取不同参数
        //V2走这个
        if(ObjectUtils.isNotEmpty(safeCheckTaskPdfDTO)&&"V2".equals(safeCheckTaskPdfDTO.getSource())){
            return getPdfGeneratorV2(safeCheckTaskPdfDTO,generatorList);
        }
        List<SafetyCheckV2Enums> templateList = SafetyCheckV2Enums.getTemplate(safeCheckTaskPdfDTO.getType());
        //zhangp 2024-03-05 九小场所-餐饮类型可能会生成多个PDF文档
        if (SafetyCheckV2Enums.A.getName().equals(safeCheckTaskPdfDTO.getType())) {
            //zhangp 2024-03-26 九小场所-餐饮类型可能会生成多个PDF文档   开始
            //九小场所

            if (CenturyCitySafePlaceTypeEnum.RESTAURANT.getName().equals(safeCheckTaskPdfDTO.getPlaceType()) ||
                    CenturyCitySafePlaceTypeEnum.COSMETOLOGY.getName().equals(safeCheckTaskPdfDTO.getPlaceType()) ||
                    CenturyCitySafePlaceTypeEnum.HEALTH.getName().equals(safeCheckTaskPdfDTO.getPlaceType())) {

                generatorList.add(new SafetyCheckPdfGenerater(SafetyCheckV2Enums.A.getTemplatCyMrYl(), String.valueOf(SafetyCheckV2Enums.A.getCode())));
            } else {
                generatorList.add(new SafetyCheckPdfGenerater(SafetyCheckV2Enums.A.getTemplat(), String.valueOf(SafetyCheckV2Enums.A.getCode())));
            }

            if (CollectionUtil.isNotEmpty(safeCheckTaskPdfDTO.getFileOutputType())) {
                //根据选择的餐饮店面销售类型生成对应的文件
                for (String index : safeCheckTaskPdfDTO.getFileOutputType()) {
                    SafetyCheckV2Enums scv = SafetyCheckV2Enums.getSafetyCheckV2EnumsByCode(Integer.parseInt(index));
                    if (ObjectUtils.isEmpty(scv)) {
                        log.error(String.format("餐饮店面销售类型文件索引为:【%s】枚举【SafetyCheckV2Enums】未找到文件", index));
                        continue;
                    }
                    generatorList.add(new SafetyCheckPdfGenerater(scv.getTemplat(), String.valueOf(scv.getCode())));
                }
            }

            /*for (SafetyCheckV2Enums scv : templateList) {
                generatorList.add(new SafetyCheckPdfGenerater(scv.getTemplat(), String.valueOf(scv.getCode())));
            }*/
            //zhangp 2024-03-26 九小场所-餐饮类型可能会生成多个PDF文档   结束
            return generatorList;
        } else if (SafetyCheckV2Enums.C.getName().equals(safeCheckTaskPdfDTO.getType())) {
            generatorList.add(new SafetyCheckPdfGenerater(SafetyCheckV2Enums.C.getTemplat(), String.valueOf(SafetyCheckV2Enums.C.getCode())));
            if (CollectionUtil.isNotEmpty(safeCheckTaskPdfDTO.getFileOutputType())) {
                //根据选择的食堂类型类型生成对应的文件
                for (String index : safeCheckTaskPdfDTO.getFileOutputType()) {
                    SafetyCheckV2Enums scv = SafetyCheckV2Enums.getSafetyCheckV2EnumsByCode(Integer.parseInt(index));
                    if (ObjectUtils.isEmpty(scv)) {
                        log.error(String.format("食堂类型文件索引为:【%s】枚举【SafetyCheckV2Enums】未找到文件", index));
                        continue;
                    }
                    generatorList.add(new SafetyCheckPdfGenerater(scv.getTemplat(), String.valueOf(scv.getCode())));
                }
            }
            return generatorList;
        }
        String templatName = SafetyCheckV2Enums.getTemplatName(safeCheckTaskPdfDTO.getType());
        if (StringUtils.isNotEmpty(templatName)) {
            generatorList.add(new SafetyCheckPdfGenerater(templatName, String.valueOf(templateList.get(0).getCode())));
        }
        generatorList.add(new LargeCompanySafePdfGenerator());
        generatorList.add(new EnterpriseSafetyInvestigationPdf());
        generatorList.add(new CampusTrainingOffDoc());
        generatorList.add(new LogisticsWarehouseDocGenerator());
        generatorList.add(new BingYangPictureGenerator());
        // 在这里添加自己的generator
        return generatorList;
    }

    private List<BaseTemplatePdfGenerator> getPdfGeneratorV2(SafeCheckTaskPdfDTO safeCheckTaskPdfDTO, List<BaseTemplatePdfGenerator> generatorList) {
        List<SafetyCheckV2Enums> templateList = SafetyCheckV2Enums.getTemplate(safeCheckTaskPdfDTO.getType());
        //zhangp 2024-03-05 九小场所-餐饮类型可能会生成多个PDF文档
        if (SafetyCheckV2Enums.A.getName().equals(safeCheckTaskPdfDTO.getType())) {
            //zhangp 2024-03-26 九小场所-餐饮类型可能会生成多个PDF文档   开始
            //九小场所
            if (CenturyCitySafePlaceTypeEnum.RESTAURANT.getName().equals(safeCheckTaskPdfDTO.getPlaceType()) ||
                    CenturyCitySafePlaceTypeEnum.COSMETOLOGY.getName().equals(safeCheckTaskPdfDTO.getPlaceType()) ||
                    CenturyCitySafePlaceTypeEnum.HEALTH.getName().equals(safeCheckTaskPdfDTO.getPlaceType())) {

                generatorList.add(new SafetyCheckPdfGenerater(SafetyCheckV2NewEnums.A.getTemplatCyMrYl(), String.valueOf(SafetyCheckV2NewEnums.A.getCode())));
            } else {
                generatorList.add(new SafetyCheckPdfGenerater(SafetyCheckV2NewEnums.A.getTemplat(), String.valueOf(SafetyCheckV2NewEnums.A.getCode())));
            }

            if (CollectionUtil.isNotEmpty(safeCheckTaskPdfDTO.getFileOutputType())) {
                //根据选择的餐饮店面销售类型生成对应的文件
                for (String index : safeCheckTaskPdfDTO.getFileOutputType()) {
                    SafetyCheckV2NewEnums scv = SafetyCheckV2NewEnums.getSafetyCheckV2EnumsByCode(Integer.parseInt(index));
                    if (ObjectUtils.isEmpty(scv)) {
                        log.error(String.format("餐饮店面销售类型文件索引为:【%s】枚举【SafetyCheckV2Enums】未找到文件", index));
                        continue;
                    }
                    generatorList.add(new SafetyCheckPdfGenerater(scv.getTemplat(), String.valueOf(scv.getCode())));
                }
            }

            /*for (SafetyCheckV2Enums scv : templateList) {
                generatorList.add(new SafetyCheckPdfGenerater(scv.getTemplat(), String.valueOf(scv.getCode())));
            }*/
            //zhangp 2024-03-26 九小场所-餐饮类型可能会生成多个PDF文档   结束
            return generatorList;
        } else if (SafetyCheckV2NewEnums.C.getName().equals(safeCheckTaskPdfDTO.getType())) {
            generatorList.add(new SafetyCheckPdfGenerater(SafetyCheckV2NewEnums.C.getTemplat(), String.valueOf(SafetyCheckV2NewEnums.C.getCode())));
            if (CollectionUtil.isNotEmpty(safeCheckTaskPdfDTO.getFileOutputType())) {
                //根据选择的食堂类型类型生成对应的文件
                for (String index : safeCheckTaskPdfDTO.getFileOutputType()) {
                    SafetyCheckV2NewEnums scv = SafetyCheckV2NewEnums.getSafetyCheckV2EnumsByCode(Integer.parseInt(index));
                    if (ObjectUtils.isEmpty(scv)) {
                        log.error(String.format("食堂类型文件索引为:【%s】枚举【SafetyCheckV2Enums】未找到文件", index));
                        continue;
                    }
                    generatorList.add(new SafetyCheckPdfGenerater(scv.getTemplat(), String.valueOf(scv.getCode())));
                }
            }
            return generatorList;
        }
        String templatName = SafetyCheckV2NewEnums.getTemplatName(safeCheckTaskPdfDTO.getType());
        if (StringUtils.isNotEmpty(templatName)) {
            generatorList.add(new SafetyCheckPdfGenerater(templatName, String.valueOf(templateList.get(0).getCode())));
        }
        generatorList.add(new LargeCompanySafePdfGenerator());
        generatorList.add(new EnterpriseSafetyInvestigationPdf());
        generatorList.add(new CampusTrainingOffDoc());
        generatorList.add(new LogisticsWarehouseDocGenerator());
        generatorList.add(new BingYangPictureGenerator());
        // 在这里添加自己的generator
        return generatorList;
    }

    @Override
    protected void afterCreatePdfSuccess(PdfCreatedBridgeBO pdfCreatedBridgeBO) {
        try {
            if (pdfCreatedBridgeBO.getReCreateFlag()) {
                // 不发送短信
                return;
            }
            Sqfw_formSummary_new formSummary = pdfCreatedBridgeBO.getFormSummaryNew();
            SafeCheckTaskPdfDTO pdfCreateField = (SafeCheckTaskPdfDTO) getPdfCreateField(formSummary);
            String operatorTelephone = pdfCreateField.getOperatorTelephone();
            if (StringUtils.isNotBlank(operatorTelephone)) {
                // 发送短信通知被检查人手机
                SmsMsgDTO smsMsgDTO = new SmsMsgDTO();
                smsMsgDTO.setPhoneNumberSet(Sets.newHashSet(operatorTelephone));

                String url = DfxyWeChatMPUtils.generatedDfxyMiniProgramUrl("/pages/user-center/safeList");
                // wzy 2024-5-29 修改为其他发送方式
                ztSmsService.ztSendSafetyCheckInfoMsg(operatorTelephone, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Aop(TransAop.READ_COMMITTED)
    protected void getPdfGenerateResAfter(List<PdfGenerateRes> pdfGenerateResList, Sqfw_formSummary_new formSummaryNew) {
        try {
            List<Sqfw_form_summary_pdf> formSummaryPdfs = Lists.newArrayList();
            boolean flag = false;
            List<Sqfw_form_summary_pdf> deletedF = Lists.newArrayList();
            int count = 0;
            for (PdfGenerateRes pdfGenerateRes : pdfGenerateResList) {
                Sqfw_formSummary_new formSummary = JSONObject.parseObject(JSON.toJSONString(pdfGenerateRes.getBusinessData()), Sqfw_formSummary_new.class);
                if (count == 0) {
                    deletedF = formSummaryPdfService.query(Cnd.where(Sqfw_form_summary_pdf::getSummaryId, "=", formSummary.getId()));
                    count++;
                }
                ByteArrayOutputStream pdfOS = pdfGenerateRes.getPdfOS();
                BaseTemplatePdfGenerator generator = pdfGenerateRes.getGenerator();
                List<ByteArrayOutputStream> osList = new ArrayList<>();
                osList.add(pdfOS);
                SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(formSummary.getParamData(), SafeCheckTaskPdfDTO.class);
                //只有九小场所存入表
                if (CenturyCitySafeServiceEnum.CENTER_CITY_NINE_SMALL_PLACE.getType().equals(safeCheckTaskPdfDTO.getType())
                        || CenturyCitySafeServiceEnum.CENTER_CITY_PERSONNEL_DENSITY.getType().equals(safeCheckTaskPdfDTO.getType())) {
                    String fileName = DownLoadFileNameEnum.getName(safeCheckTaskPdfDTO.getType());
                    String fileNameNew = DownLoadFileNameEnum.getName(safeCheckTaskPdfDTO.getType() + "-" + generator.getFileIdentity());
                    if (StringUtils.isNotBlank(fileNameNew)) {
                        fileName = fileNameNew;
                    }
                    GenerateWordAndPdfUrlVO wordVO = wordToPdfAndUpload(osList, fileName, formSummary.getUnitName() + formSummary.getType());
                    Sqfw_form_summary_pdf sqfwFormSummaryPdf = new Sqfw_form_summary_pdf();
                    sqfwFormSummaryPdf.setSummaryId(formSummary.getId());

                    sqfwFormSummaryPdf.setIndex(Integer.parseInt(generator.getFileIdentity()));
                    sqfwFormSummaryPdf.setCreateDate(new Date());
                    sqfwFormSummaryPdf.setUpdateDate(new Date());
                    //记录每一个PDF
                    if (StringUtils.isNotBlank(wordVO.getPdfUrl())) {
                        sqfwFormSummaryPdf.setUrl(wordVO.getPdfUrl());
                        sqfwFormSummaryPdf.setStatus("2");
                    } else {
                        sqfwFormSummaryPdf.setStatus("1");
                        flag = true;
                    }
                    formSummaryPdfs.add(sqfwFormSummaryPdf);
                }
            }
            if (flag) {
                log.error("CenturyCitySecurityPdfService.getPdfGenerateResAfter,生成pdf失败");
                throw new AppException("生成PDF失败！");
            }
            List<String> ids = deletedF.stream().map(Sqfw_form_summary_pdf::getId).distinct().collect(Collectors.toList());
            if (!ids.isEmpty()) {
                formSummaryPdfService.delete(ids);
            }
            formSummaryPdfService.insert(formSummaryPdfs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void beforeReGenPdf(Sqfw_formSummary_new formSummary) {
        String paramData = formSummary.getParamData();
        // 观山湖区宾阳街道
        BinyangStreetComponent.handleBeforeSubmitParam(formSummary);
        if (!paramData.equals(formSummary.getParamData())) {
            SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
            Sqfw_formSummary_new summaryNew = formsummaryNewService.fetch(formSummary.getId());
            summaryNew.setParamData(formSummary.getParamData());
            formsummaryNewService.updateIgnoreNull(summaryNew);
        }
    }

    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {
        // 观山湖区宾阳街道
        BinyangStreetComponent.handleBeforeSubmitParam(formSummary);
        // 入库商铺
        String paramData = formSummary.getParamData();
        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.toJavaObject(JSONObject.parseObject(paramData), SafeCheckTaskPdfDTO.class);

        //app2.0新字段通过上传的店铺id确定是一家
        if (StringUtils.isNotBlank(safeCheckTaskPdfDTO.getShopInfoId())) {
            SqfwShopsBaseInfo s = this.shopsBaseInfoService.fetch(safeCheckTaskPdfDTO.getShopInfoId());
            if (null != s) {
                if (StringUtils.isBlank(s.getServiceType())) {
                    s.setServiceType(SupportBusinessTypeEnum.SAFETY_CHECK.getCode());
                } else if (!s.getServiceType().contains(SupportBusinessTypeEnum.SAFETY_CHECK.getCode())) {
                    s.setServiceType(s.getServiceType() + "," + SupportBusinessTypeEnum.SAFETY_CHECK.getCode());
                }
                //原来是停业，巡检后改变状态
                if (SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(s.getShopStatus())) {
                    s.setShopStatus(SqfwFormSummaryFieldEnum.check_status_checked.getCode());
                    s.setDeleted(false);
                }
                s.setUpdateId(SecurityUtil.getUserId());
                s.setUpdateDate(LocalDateTime.now());

                this.shopsBaseInfoService.updateIgnoreNull(s);
                formSummary.setShopsBaseInfoId(s.getId());
                //app2.0 此字段用作新老数据标识存入店铺ID
                formSummary.setWorkOrderId(s.getId());
                return;
            }
            throw new ServiceException("场所不存在或已被删除！");
        }

        SqfwShopsBaseInfo shopsBaseInfo = new SqfwShopsBaseInfo();

        shopsBaseInfo.setServiceType(SupportBusinessTypeEnum.SAFETY_CHECK.getCode());
        shopsBaseInfo.setPlaceName(safeCheckTaskPdfDTO.getPlaceName());
        //shopsBaseInfo.setFillDate(DateUtil.toLocalDateTime(formSummary.getFillDate()));
        shopsBaseInfo.setOperator(safeCheckTaskPdfDTO.getSiteManager());
        shopsBaseInfo.setOperatorTelephone(safeCheckTaskPdfDTO.getOperatorTelephone());
        shopsBaseInfo.setMainBusinessScope(safeCheckTaskPdfDTO.getMainBusinessScope());
        shopsBaseInfo.setType(StringUtils.isNotEmpty(safeCheckTaskPdfDTO.getPlaceType()) ? safeCheckTaskPdfDTO.getPlaceType() : safeCheckTaskPdfDTO.getType());
        shopsBaseInfo.setType(safeCheckTaskPdfDTO.getType());
        shopsBaseInfo.setAddress(safeCheckTaskPdfDTO.getAddress());
        Sys_user user = userService.fetch(SecurityUtil.getUserId());
        String detailAddress = String.format("%s%s%s%s%s%s%s", user.getProvince(), user.getCity(), user.getDistrict(),
                user.getCounty(), user.getCommunity(), shopsBaseInfo.getAddress(), shopsBaseInfo.getPlaceName());
        shopsBaseInfo.setDetailAddress(detailAddress);
        //shopsBaseInfo.setDetailAddress(publicSecurityDTO.getAddress());
        // 检查商铺数据是否存在 存在直接返回
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup sqlGroup = cnd.where();
        sqlGroup.andEquals(SqfwShopsBaseInfo::getProvince, user.getProvince());
        sqlGroup.andEquals(SqfwShopsBaseInfo::getCity, user.getCity());
        sqlGroup.andEquals(SqfwShopsBaseInfo::getDistrict, user.getDistrict());
        sqlGroup.andEquals(SqfwShopsBaseInfo::getCounty, user.getCounty());
        if (!CommonConstants.DIRECTLY_UNDER.equals(user.getCommunity())) {
            sqlGroup.andEquals(SqfwShopsBaseInfo::getCommunity, user.getCommunity());
        }
        if (StringUtils.isNotEmpty(shopsBaseInfo.getPlaceName())) {
            String placeName = shopsBaseInfo.getPlaceName().trim();
            sqlGroup.andEquals(SqfwShopsBaseInfo::getPlaceName, placeName);
            shopsBaseInfo.setPlaceName(placeName);
        }

        if (StringUtils.isNotEmpty(shopsBaseInfo.getAddress())) {
            String address = shopsBaseInfo.getAddress().trim();
            sqlGroup.andEquals(SqfwShopsBaseInfo::getAddress, address);
            shopsBaseInfo.setAddress(address);
        }
        SqfwShopsBaseInfo s = this.shopsBaseInfoService.fetch(cnd);
        if (s != null) {
            // 不做五级更新
            s.setUpdateDate(LocalDateTime.now())
                    .setAddress(shopsBaseInfo.getAddress())
                    .setOperator(shopsBaseInfo.getOperator())
                    .setOperatorTelephone(shopsBaseInfo.getOperatorTelephone())
                    .setMainBusinessScope(shopsBaseInfo.getMainBusinessScope())
                    .setType(shopsBaseInfo.getType())
                    .setUpdateId(SecurityUtil.getUserId())
                    .setDeleted(false)
            ;
            if (StringUtils.isBlank(s.getServiceType())) {
                s.setServiceType(SupportBusinessTypeEnum.SAFETY_CHECK.getCode());
            } else if (!s.getServiceType().contains(SupportBusinessTypeEnum.SAFETY_CHECK.getCode())) {
                s.setServiceType(s.getServiceType() + "," + SupportBusinessTypeEnum.SAFETY_CHECK.getCode());
            }
            //原来是停业，巡检后改变状态
            if (SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(s.getShopStatus())) {
                s.setShopStatus(formSummary.getCheckStatus());
            }
            this.shopsBaseInfoService.updateIgnoreNull(s);
            formSummary.setShopsBaseInfoId(s.getId());
        } else {
            // 不存在 则新增
            shopsBaseInfo.setCreateDate(LocalDateTime.now())
                    .setUpdateDate(LocalDateTime.now())
                    .setCreateId(SecurityUtil.getUserId())
                    .setUpdateId(SecurityUtil.getUserId())
                    .setDeleted(false)
                    .setProvince(user.getProvince())
                    .setCity(user.getCity())
                    .setCounty(user.getCounty())
                    .setCommunity(user.getCommunity())
                    .setDistrict(user.getDistrict())
                    .setShopStatus(formSummary.getCheckStatus())
            ;
            this.shopsBaseInfoService.insert(shopsBaseInfo);
            formSummary.setShopsBaseInfoId(shopsBaseInfo.getId());
        }
    }
}
